package cn.e4j.modular.api.upload;


import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.util.AppCxt;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.FileUtil;
import cn.e4j.core.util.ToolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ImgUtils {

    private static Logger logger = LoggerFactory.getLogger(ImgUtils.class);

    public static ResponseData base64ToImg(String imgBase64) {
        BASE64Decoder decoder = new BASE64Decoder();
        String url = "";
        try {
            String baseDir = "imgs" + File.separator;

            String rootDir = System.getProperty("crm.app.wx");//window端？？

            if (ToolUtil.isEmpty(rootDir)) {
                rootDir = ".." + File.separator;
            }

            String imgDir = "i" + DateUtils.getDate(DateUtils.PATTERN_yyyyMMdd);

            //UserModel currentUser = UserUtils.getCurrentUser();
            // 文件名限定
            String localFile = rootDir
                    + "wx-uploads" + File.separator
                    + baseDir
                    + imgDir + File.separator
                    + DateUtils.getDate(DateUtils.PATTERN_yyyyMMddHHmmssSSS) + ".jpg";

            logger.info(localFile);

            FileUtil.createFolder(localFile, true);
            FileUtil.writeFile(localFile, new ByteArrayInputStream(
                    decoder.decodeBuffer(imgBase64.split("base64,")[1])));//Base64解码
            //String reUrl = rootDir.equals("null") ? localFile : localFile.replace(rootDir, "");
            String[] reUrls = localFile.split(imgDir);
            url = imgDir + reUrls[reUrls.length - 1];
        } catch (IOException e) {
            e.printStackTrace();
            return new ErrorResponseData(506,"保存图片失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(500,"保存图片异常");
        }
        return new SuccessResponseData(url);
    }

    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);

            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
